using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using NewLife;
using NewLife.Configuration;
using NewLife.Log;
using NewLife.Net;

namespace UdpServerTest
{

    public delegate void ReciveData(string ip, int port, byte[] data);
    public delegate void ClientConnect(string ip, int port);

    public class UdpServer
    {
        public string IP { get; }

        public int Port { get; }


        public event ReciveData OnReciveData;

        public event ClientConnect OnClientConnect;

        public NetServer Ns;
        private ISocketSession session;


        public UdpServer(string ip, int port)
        {
            IP = ip;
            Port = port;
        }

        public bool Start()
        {

            Ns = new NetServer(IPAddress.Parse(IP), Port, NetType.Udp);
            Ns.Log = XTrace.Log;
            Ns.NewSession += Ns_NewSession; ;
            Ns.Received += Ns_Received; ;
            Ns.Start();

            return true;
        }

        private void Ns_Received(object sender, ReceivedEventArgs e)
        {
            var data = e.Packet.ReadBytes(0, e.Packet.Count);
            OnReciveData?.Invoke(e.Remote.Address.ToString(), e.Remote.Port, data);
        }

        private void Ns_NewSession(object sender, NetSessionEventArgs e)
        {
            string ip = e.Session.Remote.Address.ToString();
            int port = e.Session.Remote.Port;
            string str = $"{e.Session.Remote.Address}:{e.Session.Remote.Port}已连接！";
            OnClientConnect?.Invoke(ip, port);
            Ns.Log.Debug(str);
        }

        public bool Send(byte[] cmd,string rip,int rport)
        {
            var temp = Ns.Sessions.Values.Select(m => m.Session).FirstOrDefault(m => m.Remote.Address.ToString() == rip && m.Remote.Port == rport);
            if (temp != null)
            {         
                string str = $"{temp.Remote.Address}:{temp.Remote.Port}发送：{cmd.ToHex(" ")}！";
                Ns.Log.Debug(str);
                var result = temp.Send(cmd);
                if (result == cmd.Length)
                {
                    return true;
                }
            }

            return false;
        }
    }
}
